package com.schoolCommunity.util;

import com.alibaba.fastjson.JSON;
import com.schoolCommunity.entity.Commodity;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;

//同步mysql插入elasticsearch
@Component
public class InsertES {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    //添加Commodity对象
    public void InsertForIndex(Commodity commodity) throws IOException {

        //创建请求
        IndexRequest request = new IndexRequest("commodity");

        //规则  PUT /yth_index/_doc/1
        //不设置id则产生随机id
        request.id(commodity.getId().toString());
        //设置超时
        request.timeout(TimeValue.timeValueSeconds(1));

        //将数据放入请求json ,需要引入fastJson
        request.source(JSON.toJSONString(commodity), XContentType.JSON);

        //客户端发送请求
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

        System.out.println(response.toString());
        System.out.println("商品插入elasticsearch状态" + response.status());  //对应命令返回的状态 CREATED


    }

    //添加修改商品对象图片
    public void UpdateCommodityPicture(String pictureURL, long id) throws IOException {
        UpdateRequest for_index = new UpdateRequest("commodity", Integer.toString((int) id));
        for_index.timeout("1s");
        //更新的数据
        Commodity commodity = new Commodity().setPictureUrl(pictureURL);
        for_index.doc(JSON.toJSONString(commodity), XContentType.JSON);
        //发送请求
        UpdateResponse update = client.update(for_index, RequestOptions.DEFAULT);
    }

    //删除对象
    public void DeleteCommodity(long id) throws IOException {
        DeleteRequest for_index = new DeleteRequest("commodity", Integer.toString((int) id));
        for_index.timeout("1s");

        DeleteResponse delete = client.delete(for_index, RequestOptions.DEFAULT);
    }

    //修改对象
    public void UpdateCommodity(Commodity commodity) throws IOException {
        Long id = commodity.getId();
        long newid = id;
        UpdateRequest for_index = new UpdateRequest("commodity", Integer.toString((int) newid));
        for_index.timeout("1s");
        //更新的数据
        for_index.doc(JSON.toJSONString(commodity), XContentType.JSON);
        //发送请求
        UpdateResponse update = client.update(for_index, RequestOptions.DEFAULT);
    }


}
